package com.example.foodtruckdemo.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description web api 中涉及到Exception的采用该方法进行统一响应
 * @ClassName WebApiExceptionHandler
 * @Author Houzhengming
 * @date 2020.06.28 11:18
 * @Version 1.0
 */
@Slf4j
@RestControllerAdvice
public class WebApiExceptionHandler{

	@ResponseBody
	@ExceptionHandler(Exception.class)
	public ApiResult webapiExceptionHandler(Exception exception) {
		log.warn("访问WarehouseWebApi错误，请检查", exception);
		return ApiResult.createFail();
	}
	@ResponseBody
	@ExceptionHandler(MaxUploadSizeExceededException.class)
	public ApiResult maxUploadSizeError(MaxUploadSizeExceededException maxUploadSizeExceededException) {
		log.warn("文件超过上传文件限制，上传失败", maxUploadSizeExceededException);
		return ApiResult.createFail("文件超过上传文件限制");
	}

	@ExceptionHandler(MethodArgumentNotValidException.class)
	@ResponseBody
	public ApiResult notValidExceptionHandler(MethodArgumentNotValidException exception) {
		Map<String, String> bindResult = getErrors(exception.getBindingResult());
		StringBuilder strBuilder = new StringBuilder();
		for (Map.Entry<String, String> result : bindResult.entrySet()) {
			log.info(String.format("错误字段：%s, 错误信息：%s", result.getKey(), result.getValue()));
			strBuilder.append("【" + result.getKey() +"】" + result.getValue() + ",");
		}
		strBuilder.deleteCharAt(strBuilder.length() - 1);
		return ApiResult.createFail(strBuilder);
	}
	/**
	 * 获取参数错误信息
	 * @param result
	 * @return
	 */
	private Map<String, String> getErrors(BindingResult result) {
		Map<String, String> map = new HashMap<>(16);
		List<FieldError> list = result.getFieldErrors();
		for (FieldError error : list) {
			map.put(error.getField(), error.getDefaultMessage());
		}
		return map;
	}

}
